/* eslint-disable react/prop-types */
/*
 * @Descripttion:
 * @version:
 * @Author: wujq
 * @Date: 2023-07-18 17:47:18
 * @LastEditors: Andy
 * @LastEditTime: 2023-08-09 10:44:41
 */

import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Cascader, Select, Button, message } from 'antd';
import PropTypes from 'prop-types';
const prefixCls = 'asset-identification-form';
import { postKnowledgeAdd, postKnowledgeUpdate } from '@api/knowledge';
import CallbackModel from '@components/callback-model';
import { withRouter } from 'react-router-dom';
import _ from 'lodash';
import { Link } from 'react-router-dom';
const { TextArea } = Input;
const formItemLayout = {
  labelCol: {
    span: 5
  },
  wrapperCol: {
    span: 19
  }
};
const lamination = [
  { value: 'application', label: '应用层' },
  { value: 'support', label: '支撑层' },
  { value: 'service', label: '服务层' },
  { value: 'system', label: '系统层' }
];
// eslint-disable-next-line react/prop-types
const AssetIdentificationForm = ({
  // eslint-disable-next-line react/prop-types
  location,
  change,
  visible,
  setVisible,
  form,
  detail,
  componentList,
  cacheRow,
  getDetail
}) => {
  const { getFieldDecorator, validateFields, resetFields, setFieldsValue } = form;
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [callBackVisble, setCallBackVisble] = useState(false);
  const [assetClassification, setAssetClassification] = useState([]);
  const closeHandler = () => {
    setVisible(false);
    resetFields();
  };
  const handleSubmit = () => {
    // eslint-disable-next-line no-unused-vars
    validateFields((err, values) => {
      if (err) {
        return;
      }
      // eslint-disable-next-line no-undefined
      setConfirmLoading(true);
      let newValues = { ...values };
      let api = !detail ? postKnowledgeAdd : postKnowledgeUpdate;
      detail ? (newValues.knowledgeId = detail._id) : '';
      const { AssetCategory } = newValues;
      newValues.topAssetCategoryOid = AssetCategory[0];
      newValues.secondAssetCategoryOid = AssetCategory[1];
      delete newValues.AssetCategory;
      Object.keys(newValues).map(r => {
        if (r !== 'isDomestic') {
          !newValues[r] ? delete newValues[r] : '';
        }
      });
      api({ ...newValues })
        .then(() => {
          message.success(!detail ? '新增成功' : '编辑成功');
          closeHandler();
          !detail && setCallBackVisble(true);
          detail && getDetail({ knowledgeId: cacheRow });
          change();
        })
        .catch(e => {
          message.error(e.message);
        })
        .finally(() => {
          setConfirmLoading(false);
        });
    });
  };
  const callbackModelFoot = () => {
    return (
      <>
        <Button type="primary" style={{ margin: '0 10px' }}>
          <Link to="/knowledge-base/custom-fingerprint?add=true">添加对应指纹规则</Link>
        </Button>
        <Button
          type="primary"
          onClick={() => {
            setVisible(true);
            setCallBackVisble(false);
          }}
        >
          继续添加指纹知识库
        </Button>
      </>
    );
  };
  useEffect(() => {
    if (componentList) {
      setAssetClassification(
        componentList.map(r => {
          r.value = r._id;
          r.label = r.name;
          r.children = r.children.map(c => {
            c.value = c._id;
            c.label = c.name;
            return c;
          });
          return r;
        })
      );
    }
  }, [componentList]);

  useEffect(() => {
    const { search } = location;
    if (search) {
      const params = new URLSearchParams(search);
      if (params.get('add')) {
        setVisible(true);
      }
    }
  }, [location]);

  useEffect(() => {
    if (detail) {
      let param = {
        name: _.get(detail, 'name.cn'),
        description: _.get(detail, 'description'),
        brandName: _.get(detail, 'brand.name.cn'),
        // brandAddress: _.get(detail, 'brand.address'),
        companyName: _.get(detail, 'company.name.cn'),
        companyReferenceLink: _.get(detail, 'company.referenceLinks[0]'),
        AssetCategory: [
          _.get(detail, 'topAssetCategoryOid'),
          _.get(detail, 'secondAssetCategoryOid')
        ],
        layer: _.get(detail, 'layer'),
        isDomestic: _.get(detail, 'isDomestic'),
        referenceLink: _.get(detail, 'referenceLinks[0]', '')
      };
      Object.keys(param).forEach(r => {
        if (!param[r] && r !== 'isDomestic') {
          param[r] = '';
        }
      });
      setFieldsValue(param);
    } else {
      resetFields();
    }
  }, [detail, visible]);
  return (
    <>
      <Modal
        title={`${detail ? '修改' : '添加'}指纹知识库`}
        maskClosable={false}
        closable={true}
        width={500}
        onCancel={closeHandler}
        onOk={handleSubmit}
        visible={visible}
        className={prefixCls}
        confirmLoading={confirmLoading}
      >
        <Form {...formItemLayout}>
          <Form.Item label="名称">
            {getFieldDecorator('name', {
              rules: [
                {
                  required: true,
                  message: '请输入指纹名称'
                }
              ]
            })(<Input placeholder="请输入指纹名称" />)}
          </Form.Item>
          <Form.Item label="描述">
            {getFieldDecorator('description')(
              <TextArea placeholder="请输入指纹描述" autosize={{ minRows: 3, maxRows: 5 }} />
            )}
          </Form.Item>
          <Form.Item label="品牌">
            {getFieldDecorator('brandName')(<Input placeholder="请输入指纹品牌" />)}
          </Form.Item>
          {/* <Form.Item label="品牌官方地址">
            {getFieldDecorator('brandAddress')(<Input placeholder="请输入指纹品牌官方地址" />)}
          </Form.Item> */}
          <Form.Item label="厂商">
            {getFieldDecorator('companyName')(<Input placeholder="请输入指纹厂商" />)}
          </Form.Item>
          <Form.Item label="厂商官方网址">
            {getFieldDecorator('companyReferenceLink')(<Input placeholder="请输入厂商官方网址" />)}
          </Form.Item>
          <Form.Item label="资产分类">
            {getFieldDecorator('AssetCategory', {
              rules: [
                {
                  required: true,
                  message: '请输入资产分类'
                }
              ]
            })(<Cascader options={assetClassification} placeholder="请选择资产分类" />)}
          </Form.Item>
          <Form.Item label="分层">
            {getFieldDecorator('layer', {
              rules: [
                {
                  required: true,
                  message: '请选择指纹分层'
                }
              ]
            })(
              <Select
                value={Select}
                // onSelect={this.onMultiChange}
                className="multi-select"
                placeholder="请选择指纹分层"
              >
                {lamination.map((r, i) => {
                  return (
                    <Select.Option value={r.value} key={i}>
                      {r.label}
                    </Select.Option>
                  );
                })}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="参考链接">
            {getFieldDecorator('referenceLink')(<Input placeholder="请输入参考链接" />)}
          </Form.Item>
          <Form.Item label="是否国产化">
            {getFieldDecorator('isDomestic', {
              rules: [
                {
                  required: true,
                  message: '请选择是否国产化'
                }
              ]
            })(
              <Select
                value={Select}
                // onSelect={this.onMultiChange}
                className="multi-select"
                placeholder="请选择是否国产化"
              >
                <Select.Option value={true}>是</Select.Option>
                <Select.Option value={false}>否</Select.Option>
              </Select>
            )}
          </Form.Item>
        </Form>
      </Modal>
      <CallbackModel
        visible={callBackVisble}
        setVisible={setCallBackVisble}
        footer={callbackModelFoot()}
        title="添加指纹知识库成功"
        content="是否继续添加指纹知识库"
      />
    </>
  );
};

AssetIdentificationForm.propTypes = {
  visible: PropTypes.bool,
  setVisible: PropTypes.func,
  form: PropTypes,
  edit: PropTypes.bool
};
export default withRouter(Form.create({ name: 'AssetIdentificatioForm' })(AssetIdentificationForm));
